package ltd.hxya.novel.springsecurity.filter;

import com.alibaba.fastjson.TypeReference;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import ltd.hxya.novel.common.bean.ResultEnum;
import ltd.hxya.novel.common.constant.JwtConstant;
import ltd.hxya.novel.common.constant.SecurityConstant;
import ltd.hxya.novel.common.constant.redis.RedisConstant;
import ltd.hxya.novel.common.exception.NovelGlobalException;
import ltd.hxya.novel.common.utils.JwtUtils;
import ltd.hxya.novel.common.utils.RedisUtils;
import ltd.hxya.novel.springsecurity.entity.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class AuthorizeFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(JwtConstant.TOKEN_HEADER_ADMIN_KEY);
        UserDetail userDetail  =null;
        //从请求头中取出是否内部调用
        String isAuth = request.getHeader(SecurityConstant.IS_AUTHENTICATION);
        if (!StringUtils.isEmpty(isAuth)&&Boolean.parseBoolean(isAuth)){
            //如果需要认证，不做任何操作，不需要认证，则添加权限为*
            userDetail=new UserDetail();
            List<String> permissions = new ArrayList<>();
            permissions.add("*");
            userDetail.setPermissions(permissions);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request,response);
            return;
        }
        if (StringUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }
        //如果登录了，则从redis中取出相关信息，并放到SecurityContextHolder中

        try {
            String userIdStr = JwtUtils.checkToken(token);
            userDetail = redisUtils.get(RedisConstant.ADMIN_USER_KEY+userIdStr, new TypeReference<UserDetail>() {
            });
        }catch (ExpiredJwtException exception){
            throw new NovelGlobalException(ResultEnum.USER_TOKEN_EXPIRE.getCode(), ResultEnum.USER_TOKEN_EXPIRE.getMsg());
        }

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
